import datetime
import json
import time
from typing import Dict, Optional
from sqlalchemy.orm import Session
import prometheus_client
from prometheus_client import Counter, Gauge
from prometheus_client.core import CollectorRegistry

from core.response import resp_500
from core.logger import logger
from app.monitor_doris.models.monitor_doris_http_record import MonitorDorisHttpRecord
from app.monitor_doris.models.monitor_doris_http_url import MonitorDorisHttpUrl
from common.welab_doris import WelabDoris
from common.utils import CommonTimeUtils, cst_to_utc

from setting import config


class MonitorDorisHttpRecordHandler():
    """  MonitorDorisHttpRecord Handler
    """
    def __init__(self):
        self.welab_doris = WelabDoris()
        self.doris_table = config.DORIS_HTTP_TABLE


    def get_http_record_search(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        根据表字段模糊匹配，获取http的url记录信息
        """
        try:
            field_info = {field: value}
            order_info = {"update_at": "desc"}
            result = MonitorDorisHttpRecord.filter_by_field_search(db, page, per_page, field_info, order_info)
            if not result:
                logger.warning(f"get http url record search, result is null => {field}:{value}")
                return False, None

        except Exception as e:
            message = f"get http url record search by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True, result



    def get_http_record_match(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        根据表字段完全匹配，获取http的url记录信息
        """
        try:
            result = MonitorDorisHttpRecord.filter_by_field_match(db, page, per_page, {field: value})
            if not result:
                logger.warning(f"get http url record match, result is null => {field}:{value}")
                return False, None

        except Exception as e:
            message = f"get http url record match by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True, result




    def delete_http_record(self, db: Session, data: dict):
        """
        删除http的url记录信息
        """
        try:
            apprecord_object = MonitorDorisHttpRecord.get_object_by_uuid(db, data['uuid'])
            if not apprecord_object:
                # 如果不存在， 则异常返回
                logger.error(f"delete http url record failed, uuid:{data['uuid']} not exist")
                return False

            # 删除告警记录
            MonitorDorisHttpRecord.delete_object_by_uuid(db, data['uuid'])
        except Exception as e:
            message = f"delete http url record uuid:{data['uuid']}  error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return True



    def get_http_record_state(self, db: Session):
        """
        获取http接口状态记录是否正常更新
        """
        try:
            end_time = datetime.datetime.now()
            begin_time = end_time - datetime.timedelta(minutes=70)
            http_records = MonitorDorisHttpRecord.get_object_info_for_time(db, begin_time, end_time)
            if not http_records:
                logger.error("get http url records for time failed")
                return False
        except Exception as e:
            message = f"get http url records for time error => {e}"
            logger.exception(f"{message} => {e}")
            return False

        return True
    
    
    
    def get_http_record_agg(self, cst_begin_time, cst_end_time, url_info):
        """
        从doris数据库获取接口的状态码信息
        """
        try:
            url_record = {
                "domain": url_info["domain"],
                "url": url_info["url"],
                "method": url_info["method"],
                "provider": url_info["provider"],
                "production": url_info["production"],
                "total": 0,
                "status2xx": 0,
                "status2xx_req_avg": 0,
                "status2xx_resp_avg": 0,
                "status3xx": 0,
                "status3xx_req_avg": 0,
                "status3xx_resp_avg": 0,
                "status4xx": 0,
                "status4xx_req_avg": 0,
                "status4xx_resp_avg": 0,
                "status5xx": 0,
                "status5xx_req_avg": 0,
                "status5xx_resp_avg": 0,
                "begin_time": cst_begin_time,
                "end_time": cst_end_time,
                "comment": url_info["comment"]
            }
            
            result, datas = self.welab_doris.get_http_record_agg(self.doris_table, url_info["domain"],
                                                          url_info["url"], url_info["method"],
                                                          cst_begin_time, cst_end_time)
            if result == False:
                logger.error(f"doris get http record agg failed=> {json.dumps(url_record)} ")
                return False
        
            for data in datas:  
                url_record.update({
                    f"status{data['response_group']}": data["total_count"],
                    f"status{data['response_group']}_req_avg": round(float(data["avg_req_time"]), 2),
                    f"status{data['response_group']}_resp_avg": round(float(data["avg_req_time"]), 2)
                })
                url_record["total"] += data["total_count"]
            logger.info(f"doris get http record agg success=> {json.dumps(url_record)} ")
        except Exception as e:
            logger.error(f"doris get http record agg failed=> {json.dumps(url_record)} => error => {e}")
            return False
            
        return url_record
    
    
    
    
    def task_update_from_doris_handle(self, db: Session, interval_min: int):
        """
        从doris数据库获取接口的状态码信息保存到mysql数据库的任务处理
        """
        # 获取搜索时间段
        now = datetime.datetime.now()
        cst_end_time = now.strftime("%Y-%m-%d %H:%M:%S")
        cst_begin_time = (now - datetime.timedelta(minutes=interval_min)).strftime("%Y-%m-%d %H:%M:%S")
        
        # 获取所有的接口信息
        url_infos = MonitorDorisHttpUrl.get_object_info_for_used(db)
        for url_info in url_infos:
            # 从doris数据库获取接口的状态码信息
            url_record = self.get_http_record_agg(cst_begin_time, cst_end_time, url_info)
            if not url_record:
                logger.error(f"get htt record agg for http_code failed")
                return False
            
            # 结果保存到mysql数据库
            result = MonitorDorisHttpRecord.add(db, url_record)
            if not result:
                logger.error(f"add http record to database failed")
                return False
            
        logger.info("all url infos handle success")
        return True
            
            
        
    def get_http_all_metrics(self, db: Session):
        """
        将http的url状态信息返回到prometheus
        """
        # 配置两个指标
        registry = CollectorRegistry(auto_describe=False)
        welab_http_code = Gauge("welab_http_code", "url http code number",
                             ["domain", "url", "method", "provider", "http_code"], registry=registry)
        
        welab_http_time = Gauge("welab_http_time", "url http avg time",
                             ["domain", "url", "method", "provider", "http_time"], registry=registry)
        
        # 获取最近的http接口状态信息
        is_update = []
        end_time = datetime.datetime.now()
        begin_time = end_time - datetime.timedelta(minutes=70)
        http_records = MonitorDorisHttpRecord.get_object_info_for_time(db, begin_time, end_time)
        if not http_records:
            logger.error("get http url records for time failed")
            return False
        
        for http_record in http_records:
            # 避免重复的接口信息
            http_record_id = http_record["domain"]+http_record["url"]+http_record["method"]+http_record["provider"]
            if http_record_id in is_update:
                continue
            
            # 配置welab_http_code指标
            for http_code in ["total", "status2xx", "status3xx", "status4xx", "status5xx"]:
                welab_http_code.labels(domain=http_record["domain"],
                                    url=http_record["url"],
                                    method=http_record["method"],
                                    provider=http_record["provider"],
                                    http_code=http_code).set(http_record[http_code])
                
            # 配置welab_http_time指标
            for http_time in ["status2xx_req_avg", "status2xx_resp_avg",
                              "status3xx_req_avg", "status3xx_resp_avg",
                              "status4xx_req_avg", "status4xx_resp_avg",
                              "status5xx_req_avg", "status5xx_resp_avg"]:
                welab_http_time.labels(domain=http_record["domain"],
                                    url=http_record["url"],
                                    method=http_record["method"],
                                    provider=http_record["provider"],
                                    http_time=http_time).set(http_record[http_time])
            is_update.append(http_record_id)
                
        return prometheus_client.generate_latest(registry)
    
    
def main():
    from common.database import SessionLocal
    session = SessionLocal()
    interval_min = 5


    monitor_doris_http_record_handler = MonitorDorisHttpRecordHandler()
    result = monitor_doris_http_record_handler.get_http_all_metrics(session)
    # result = monitor_doris_http_record_handler.task_update_from_doris_handle(session, interval_min)
    print(result)



if __name__ == "__main__":
    main()

            

